<!-- 账号管理 -->
<template>
<div class="dashboard-editor-container">
  <el-row style="background: #fff; padding: 16px;">
    <!-- <div style="color:rgb(96, 98, 102);margin-bottom:20px;">
        <span style="font-size:14px">网络隔离策略：</span>
        <el-radio-group v-model="Mode" @change="submit(false)">
            <el-radio :label="4" >智能模式</el-radio>
            <el-radio :label="3">禁止网卡</el-radio>
            <el-radio :label="1">黑名单模式</el-radio>
            <el-radio :label="2">白名单模式</el-radio>
        </el-radio-group>
    </div> -->
    <div style="display:flex;justify-content:space-between;">
        
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()" >添加规则</el-button>
          <span style="color:red;font-size:14px;padding-left:20px;">通过拖动表格行来重新排列顺序, 当前顺序将影响执行顺序。</span>
          <!-- :disabled="Mode == 3 || Mode == 4" -->
        </div>
      </div>
    <el-table stripe border :data="tableData" class="draggable-table" row-key="RuleName" style="width: 100%; margin-top: 15px;">
      <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
        <el-table-column label="规则名称" prop="RuleName"  show-overflow-tooltip></el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj"  >
          <template slot-scope="{row}">
            <span>{{ row.DeviceObj.length === 0 ? '全部' : row.DeviceObj.join(',') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模式" show-overflow-tooltip prop="IsValid" >
          <template slot-scope="{row}">
            <span>{{ row.Mode === 1 ? '智能模式' : row.Mode === 2 ? '禁止网卡' : '不隔离' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp" ></el-table-column>
        <el-table-column label="操作"  width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row, scope.$index)" >删除</el-button>
          </template>
        </el-table-column>
        
        <!-- <el-table-column label="协议" show-overflow-tooltip prop="Protocol" width="160" >
            <template slot-scope="scope">
                <span>{{ protocolMap[scope.row.Protocol] }}</span>
            </template>
        </el-table-column>
        <el-table-column label="源地址" show-overflow-tooltip prop="SrcIP"  ></el-table-column>
        <el-table-column label="源端口" show-overflow-tooltip prop="SrcPort" > </el-table-column>
        <el-table-column label="目的地址" show-overflow-tooltip prop="DstIP"  ></el-table-column>
        <el-table-column label="目的端口" show-overflow-tooltip prop="DstPort" > </el-table-column>
        <el-table-column label="操作"  width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row, scope.$index)" >删除</el-button>
          </template>
        </el-table-column> -->
    </el-table>
  </el-row>
  <el-dialog
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape=false
    :title="Action === 1 ? '添加规则' : '修改规则' "
    :visible.sync="dialogVisible"
    v-el-drag-dialog
    width="700px">
      <el-form label-width="130px" :model="accountForm" :rules="rules2" ref="accountForm">
        <el-row >
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称:' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName"  :disabled="Action !== 1" :maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则生效:' prop="IsValid">
              <el-switch v-model="accountForm.IsValid" :active-value="1" :inactive-value="0" active-color="#3a8adb" inactive-color="#ccc"></el-switch>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='应用对象:' prop="DeviceObjType">
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="2">指定校区</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-cascader
                v-if="accountForm.DeviceObjType !== 8"
                :disabled="accountForm.DeviceObjType === 1" 
                multiple 
                style="width:100%;" 
                :placeholder="`${accountForm.DeviceObjType === 1 ? '全部' : accountForm.DeviceObjType === 2 ? '请选择校区' : '请选择资产'}`"
                ref="cascaderAddr"
                v-model="accountForm.DeviceObj"
                clearable
                :options="DeviceObjList"
                :props="{ label: 'SubClass', value: 'SubClass', emitPath: false, multiple: true, checkStrictly: false}"
                @change="handleChange">
              </el-cascader>
              <el-select v-if="accountForm.DeviceObjType === 8" style="width:100%" v-model="accountForm.DeviceObj" multiple placeholder="请选择角色">
                <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role" :value="item.Role"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='执行模式:' prop="Mode">
              <el-radio v-model="accountForm.Mode"   :label="1">智能模式</el-radio>
              <el-radio v-model="accountForm.Mode"   :label="2">禁止网卡模式</el-radio>
              <el-radio v-model="accountForm.Mode"   :label="3">不隔离</el-radio>
            </el-form-item> 
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" :rows="3"  v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row >
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='协议' prop="Protocol">
              <el-select v-model="accountForm.Protocol" style="width:100%" placeholder="请选择协议">
                <el-option label="全部" :value="0"></el-option>
                <el-option label="TCP"  :value="6"></el-option>
                <el-option label="UDP"  :value="17"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="15" :lg="15">
            <el-form-item label='源地址:' prop="SrcIP">
              <el-input v-model="accountForm.SrcIP"  oninput="value=value.replace(/[^0-9./-]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="9" :sm="9" :lg="9" style="margin-top:10px;">
            <span style="color:#aaa;">
              （空表示全部，支持单个IP和IP区间）
            </span>
          </el-col>
          <el-col :xs="15" :sm="15" :lg="15">
            <el-form-item label='源端口:' prop="SrcPort">
              <el-input v-model="accountForm.SrcPort" oninput="value=value.replace(/[^0-9,-]/g,'')" placeholder="请输入端口"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="9" :sm="9" :lg="9" style="margin-top:10px;">
            <span style="color:#aaa;">
              （空表示全部，支持多个端口和区间）
            </span>
          </el-col>
          <el-col :xs="15" :sm="15" :lg="15">
            <el-form-item label='目的地址:' prop="DstIP">
              <el-input v-model="accountForm.DstIP"  oninput="value=value.replace(/[^0-9./-]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="9" :sm="9" :lg="9" style="margin-top:10px;">
            <span style="color:#aaa;">
              （空表示全部，支持单个IP和IP区间）
            </span>
          </el-col>
          <el-col :xs="15" :sm="15" :lg="15">
            <el-form-item label='目的端口:' prop="DstPort" >
              <el-input v-model="accountForm.DstPort" oninput="value=value.replace(/[^0-9,-]/g,'')" placeholder="请输入端口"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="9" :sm="9" :lg="9" style="margin-top:10px;">
            <span style="color:#aaa;">
              （空表示全部，支持多个端口和区间）
            </span>
          </el-col>
        </el-row> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit(true)">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { GetallSchool, GetallAssets } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
export default {
directives: { elDragDialog },
data() {
return {
  pageNum: 1,
  pageSize: 10,
  Mode:4,
  tableData: [],
  RoleList: [],
  Action: 1,
  dialogVisible: false,
  accountForm: {},
  moderow:-1,
  DeviceObjList: [],
  rules2: {
    RuleName: [
      { required: true, message: "请输入规则名称"}
    ],
  },
  rules: {
    SrcIP: [
          {  message: '请输入正确IP地址或范围', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const ipOrRang = /^(?:(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)(?:-(?:(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d))?$/;
              if (value && !ipOrRang.test(value.trim())) {
                callback(new Error('请输入正确的IP地址或范围'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
    SrcPort: [
      { required: false },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback();
            return;
          }
          const ports = value.split('-');
          if (ports.length > 2) {
            callback(new Error('请输入正确的端口号或端口区间'));
            return;
          }
          for (let i = 0; i < ports.length; i++) {
            const port = ports[i];
            if (!/^\d+$/.test(port) || parseInt(port, 10) < 1 || parseInt(port, 10) > 65535 || (port.length > 1 && port[0] === '0')) {
              callback(new Error('端口号必须介于1和65535之间'));
              return;
            }
          }
          if (ports.length === 2 && parseInt(ports[0], 10) >= parseInt(ports[1], 10)) {
            callback(new Error('端口区间起始端口必须小于结束端口'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    DstIP: [
          {  message: '请输入正确IP地址或范围', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const ipOrRangeRegex = /^(?:(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)(?:-(?:(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d))?$/;
              if (value && !ipOrRangeRegex.test(value.trim())) {
                callback(new Error('请输入正确的IP地址或范围'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
    DstPort: [
          { required: false },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
                return;
              }
              const ports = value.split('-');
              if (ports.length > 2) {
                callback(new Error('请输入正确的端口号或端口区间'));
                return;
              }
              for (let i = 0; i < ports.length; i++) {
                const port = ports[i];
                if (!/^\d+$/.test(port) || parseInt(port, 10) < 1 || parseInt(port, 10) > 65535 || (port.length > 1 && port[0] === '0')) {
                  callback(new Error('端口号必须介于1和65535之间'));
                  return;
                }
              }
              if (ports.length === 2 && parseInt(ports[0], 10) >= parseInt(ports[1], 10)) {
                callback(new Error('端口区间起始端口必须小于结束端口'));
                return;
              }
              callback();
            },
            trigger: 'blur'
          }
        ],
  },
  protocolMap: {
        0: "全部",
        6: "TCP",
        17: "UDP"
      }
}
},
//生命周期 - 创建完成（访问当前this实例）
created() {
  this.getData()
},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {
  this.initSort();
},
methods: {
  initSort() {
    const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
    // 根据具体需求配置options配置项
    const sortable = new Sortable(el, {
      animation: 500, // 拖拽时的动画时长
      onEnd: async (evt) => { // 监听拖动结束事件
        // 下面将拖拽后的顺序进行修改
        const currRow = this.tableData.splice(evt.oldIndex, 1)[0]
        this.tableData.splice(evt.newIndex, 0, currRow)
        const newData = []
        this.tableData.forEach((item, index) => {
          newData[index] = {
            id: item.id,
            rank: index + 1
          }
        })
        const data = {
          Data:{
            OpFile: 1,
            List : [...this.tableData]
          }
        }
        const res = await connrequest('ReorderList', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('排序成功')
          this.getData()
        }
      }
    })
  },
  async getData(){
    const res = await connrequest('GetForbiddenNetRule')
    this.tableData = res.Data || []
  },
  async DeviceObjTypeChange(value){
    this.$set(this.accountForm, 'DeviceObj', '')
    if(value === 0){
      this.DeviceObjList = []
    }else if(value === 2){
      const res = await this.GetSchoolStatusSumTree()
      this.DeviceObjList = [res]
    }else if(value === 8){
      const res = await this.GetRolestatus()
      this.RoleList = res 
    }else{
      const res = await this.GetDeviceStatusSumTree()
      this.DeviceObjList = [res]
    }
  },
  // 获取校区树
  async GetSchoolStatusSumTree() {
    const res = await connrequest('GetDeviceStatusSumTree')
    return GetallSchool(res.Data)
  },
  // 获取角色
  async GetRolestatus() {
    const res = await connrequest('GetParamDictRole')
    return res.Data
  },
  // 获取资产树
  async GetDeviceStatusSumTree() {
    const res = await connrequest('GetDeviceStatusSumTree')
    return GetallAssets(res.Data)
  },
  addClick(){
    this.Action = 1
    this.dialogVisible = true
    this.$nextTick(()=>{
      if (this.$refs['accountForm']) {
        this.accountForm = {
          // IsValid: 1,
          DeviceObjType: 1,
          Mode:1,
          DeviceObj:[]
        }
      }
      this.$refs['accountForm'].resetFields();
    })
    // this.moderow = -1
    // this.Action = 1
    // this.dialogVisible = true
    // this.$nextTick(()=>{
    //   this.accountForm = {
    //     Protocol: 0,
    //   }
    //   this.$refs['accountForm'].resetFields();
    // })
  },
  changeClick(row, index){
    this.Action = 2
    this.DeviceObjTypeChange(row.DeviceObjType)
    this.moderow = index
    this.$nextTick(()=>{
      this.accountForm = {...row}
      this.$refs['accountForm'].resetFields();
    })
    this.dialogVisible = true
  },
  deleteClick(row){
    this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let data = {
        Data: {
          Action: 3,
          Detail: {...row}
        }
      }
      const res = await connrequest('EditForbiddenNetRule', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        this.dialogVisible = false
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
  },
  async submit(control) {
    if (!control&&true) {
      await this.sendData();
    } else {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          // if (this.moderow !== -1) {
          //   this.tableData[this.moderow] = this.accountForm;
          // } else {
          //   this.tableData.push(this.accountForm);
          // }
          await this.sendData();
        }
      });
    }
  },
  async sendData() {
    let data = {
      Data: {
        Action:this.Action ,
        Detail: {
          ...this.accountForm
        }
      }
    };
    const res = await connrequest('EditForbiddenNetRule', data);
    if (res.Status.StatusCode === 0) {
      this.getData();
      this.dialogVisible = false;
    }
  },
  handleChange(){}
}
}
</script>